# -*- coding: utf-8 -*-
from datetime import datetime
import traceback
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from core.decorators import render
from core.enum import REQUEST_GET, RESPONSE_ERROR, RESPONSE_SUCCESS
from ..models import Record

UPDATE_METHOD_INCREASE = 0
UPDATE_METHOD_DECREASE = 1

@csrf_exempt
@render(type='json')
def update(request, record_pk, method):
    if request.method == REQUEST_GET:
        raise Http404
    else:
        try:
            request.session.set_expiry(datetime(2029, 12, 1, 0, 0, 0))
            if not request.session.get('rating_votes', None):
                request.session['rating_votes'] = []

            record = Record.objects.get(pk = record_pk)

            if record.pk in request.session['rating_votes']:
                raise Exception("Already voted")

            if int(method) == UPDATE_METHOD_INCREASE:
                record.rating += 1
            elif int(method) == UPDATE_METHOD_DECREASE:
                record.rating -= 1
            else:
                raise Exception("Undefined update method")
            record.save()

            request.session['rating_votes'].append(record.pk)

            return {
                'code': RESPONSE_SUCCESS,
                'message': "Рейтинг успешно обновлен",
                'rating': record.rating
            }

        except Exception, e:
            traceback.print_exc()
            return {
                'code': RESPONSE_ERROR,
                'message': "Ошибка изменения рейтинга. Пожалуйста сообщите администрации сайта."
            }